package com.tanhua.dubbo.api;


import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.Counts;
import com.tanhua.model.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class CountsApiImpl implements CountsApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Counts getCount(Long userId) {

        Counts counts=new Counts();
        Integer fancount = 0;
        Integer loveCount = 0;
        Integer eachLoveCount = 0;

        //获取粉丝
        List<UserLike> likeList = mongoTemplate
                .find(Query.query(Criteria
                        .where("likeUserId")
                        .is(userId)), UserLike.class);
        for (UserLike like : likeList) {
            if (like.getIsLike()){
                fancount++;
            }
        }
        //获取喜欢
        List<UserLike> LoveId = mongoTemplate
                .find(Query.query(Criteria
                .where("userId")
                .is(userId)), UserLike.class);
        List<ObjectId> likeUserId = CollUtil.getFieldValues(LoveId, "id", ObjectId.class);

        for (ObjectId id : likeUserId) {
            Boolean isLike = mongoTemplate.findById(id, UserLike.class).getIsLike();
            if (isLike){
                loveCount++;
            }
        }
        Long likeUserId1 = mongoTemplate.findById(likeUserId, UserLike.class).getLikeUserId();
        //获取互相喜欢

        List<UserLike> eachLoves = mongoTemplate
                .find(Query.query(Criteria
                        .where("likeUserId")
                        .is(userId).and("userId").is(likeUserId1)), UserLike.class);
        for (UserLike eachLove : eachLoves) {
            if (eachLove.getIsLike()){
                eachLoveCount++;
            }
        }

        counts.setFanCount(fancount);
        counts.setLoveCount(loveCount);
        counts.setEachLoveCount(eachLoveCount);
        return counts;
    }
}
